enyo.kind({
    name: "MyApps.GolfClubsAround",
    kind: enyo.VFlexBox,
    events: {
        onBack: "",
    },
    components: [    /**
     * Services
     */
    {
        name: "getData",
        kind: "WebService",
        url: "http://golfplus.mobile2you.fr/golfs.json",
        onSuccess: "gotData",
        onFailure: "gotDataFailure"
    }, {
        name: "getPosition",
        kind: "PalmService",
        service: "palm://com.palm.location/",
        method: "getCurrentPosition",
        onSuccess: "gotPosition",
        onFailure: "gotPositionFailure",
        subscribe: true
    },    /**
     * Layout
     */
    {
        name: "pane",
        kind: "Pane",
        flex: 1,
        transitionKind: "enyo.transitions.LeftRightFlyin",
        components: [{
            kind: "VFlexBox",
            className: "whitebackground",
            components: [{
                kind: "RadioGroup",
                onChange: "switchView",
                className: "radiogroup",
                components: [{
                    label: "Liste"
                }, {
                    label: "Carte"
                }, ]
            }, {
                name: "pane2",
                kind: "Pane",
                flex: 1,
                components: [{
                    name: "list",
                    kind: "VirtualList",
                    className: "golfclubslist",
                    flex: 1,
                    onSetupRow: "listSetupRow",
                    components: [{
                        kind: "Item",
                        layoutKind: "VFlexLayout",
                        components: [{
                            name: "itemLabel",
                        
                        }, {
                            className: "golfclubdistance",
                            name: "rowLabel"
                        }],
                        onclick: "listItemClick"
                    }]
                }, {
                    name: "map",
                    kind: "Map",
                    credentials: "AsuRnAEKCnBbZ8CpIw7cJZqHeVjZSvpKbJedQzy0Th1Cr_BxhHvK8eL4-zQsiP_k",
                    zoom: 9,
                
                }, ]
            }, ]
        },        /**
         * Components definition
         */
        {
            name: "golfViewDetails",
            kind: "MyApps.GolfClubDetail",
            onBack: "goBack",
            lazy: true,
        }, ]
    }, ],
    
    
    create: function(){
        this.inherited(arguments);
        this.position = [];
        //all clubs
        this.rawdata = [];
        //filtered by gps position
        this.data = [];
        this.golfData = [];
        this.$.getPosition.call();
        this.$.pane2.selectViewByName("list");
    },
    
    switchView: function(){
    
        if (this.$.pane2.getViewName() == "map") {
            this.$.pane2.selectViewByName("list");
        }
        else 
            if (this.$.pane2.getViewName() == "list") {
                this.$.pane2.selectViewByName("map");
                this.showPinsOnMap();
            }
    },
    
    gotPosition: function(inSender, inResponse){
        this.position = inResponse;
        console.log("gps success ");
        this.$.map.setCenter(this.position.latitude, this.position.longitude);
        this.$.getData.call();
    },
    
    gotPositionFailure: function(inSender, inResponse){
        console.log("gps failure ");
    },
    
    goBack: function(inSender, inEvent){
        this.$.pane.back(inEvent);
    },
    
    gotData: function(inSender, inResponse){
        this.rawdata = inResponse;
        var i = 0;
        console.log("got Data");
        for (x in this.rawdata) {
            var distance = this.distanceFromMe(this.rawdata[x].golf.latitude, this.rawdata[x].golf.longitude);
            
            if (distance < 20) {
                this.data[i] = this.rawdata[x];
                this.data[i].golf.distance = distance;
                i++;
            }
        }
        
        this.$.list.refresh();
    },
    gotDataFailure: function(inSender, inResponse){
        console.log("got failure from getData");
    },
    listSetupRow: function(inSender, inRow){
        var f = this.data[inRow];
        if (f) {
            this.$.itemLabel.setContent(f.golf.nom);
            this.$.rowLabel.setContent(f.golf.distance + " km");
            return true;
        }
    },
    listItemClick: function(inSender, inEvent){
        var golf = this.data[inEvent.rowIndex];
        this.$.pane.selectViewByName("golfViewDetails");
        this.$.golfViewDetails.setGolf(golf);
    },
    goBack: function(inSender, inEvent){
        this.$.pane.back(inEvent);
    },
    
    distanceFromMe: function(lat2, lon2){
        lat1 = this.position.latitude;
        lon1 = this.position.longitude;
        var R = 6371; // km  Earth 
        var dLat = (lat2 - lat1) * Math.PI / 180;
        var dLon = (lon2 - lon1) * Math.PI / 180;
        var lat1 = lat1 * Math.PI / 180;
        var lat2 = lat2 * Math.PI / 180;
        
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        var d = R * c;
        return Math.round(d * 10) / 10;
    },
    showPinsOnMap: function(){
    
        var bingmap = this.$.map.hasMap();
        bingmap.entities.clear();
        
        var pushpinOptions = {
            icon: 'images/poi_custom.png'
        };
        var pushpin = new Microsoft.Maps.Pushpin(bingmap.getCenter(), pushpinOptions);
        bingmap.entities.push(pushpin);
        
        
        for (x in this.data) {
            var pushpin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(this.data[x].golf.latitude, this.data[x].golf.longitude), null);
            bingmap.entities.push(pushpin);
        }
        
        
        
        //        var thickness = 10;
        //        var options = {
        //            fillColor: new Microsoft.Maps.Color(150, 150, 0, 150),
        //            strokeColor: new Microsoft.Maps.Color(100, 100, 0, 100),
        //            strokeThickness: parseInt(thickness)
        //        };
        //        var locations = this.getLocationsForCircle();
        //        
        //        var polygon = new Microsoft.Maps.Polygon(locations, options);
        //        bingmap.entities.push(polygon);
    },
    
    //for unknown reason it draw elipse not circle (it's sin and cos mistakes or gps points are not in circle)   
    getLocationsForCircle: function(){
    
        var a = this.position.latitude;
        var b = this.position.longitude;
        var r = 0.1;
        var locations = new Array();
        var i = 0;
        
        
        
        for (var t = 0; t <= 64; t++) {
            var x = a + r * Math.cos((t * Math.PI) / 32);
            var y = b + r * Math.sin((t * Math.PI) / 32);
            x = Math.round(x * 10000) / 10000;
            y = Math.round(y * 10000) / 10000;
            locations[i] = new Microsoft.Maps.Location(x, y);
            i++;
        }
        return locations;
    }
    
});

